package top.taven.http;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Base64;

public class ApacheHttpDemo {

    public static void main(String[] args) {

        try{

            Demo1();

        }catch (Exception e){
            e.printStackTrace();
        }


    }

    public static void Demo1() throws Exception {

        CloseableHttpClient httpClient = HttpClients.createDefault();

        URIBuilder uriBuilder = new URIBuilder("https://4.ipw.cn");

        uriBuilder.addParameter("abc", "123");

        HttpGet httpGet = new HttpGet(uriBuilder.build());

        httpGet.setHeader("abc", "123");

        CloseableHttpResponse response = httpClient.execute(httpGet);


        //System.out.println(response.toString());
        System.out.println(response.getStatusLine().getStatusCode());
        System.out.println(response.getEntity().getContentLength());
        //System.out.println(response.getEntity().getContent());

        final byte[] bytes = EntityUtils.toByteArray(response.getEntity());
        System.out.println(new String(bytes));

        final String responseData = Base64.getEncoder().encodeToString(bytes);
        System.out.println(responseData);


    }

    public static void downloadAndSave(String url, File file) throws IOException {
        CloseableHttpClient client = HttpClientBuilder.create().build();

        try (CloseableHttpResponse response = client.execute(new HttpGet(url))) {
            HttpEntity entity = response.getEntity();
            if (entity != null) {

                try (FileOutputStream outstream = new FileOutputStream(file)) {

                    entity.writeTo(outstream);
                    outstream.flush();

                }
            }
        }
    }

}